<template>
  <div class="home-layout">
    <aside class="sidebar">
      <h1>风行旅途</h1>
      <hr class="sidebar-divider" />
      <nav>
        <ul>
          <li>
            <a
              href="#"
              :class="{ active: activeTab === 'train' }"
              @click.prevent="setActive('train')"
              >火车购票</a
            >
          </li>
          <li>
            <a
              href="#"
              :class="{ active: activeTab === 'hotel' }"
              @click.prevent="setActive('hotel')"
              >酒店</a
            >
          </li>
          <li>
            <a href="#" :class="{ active: activeTab === 'meal' }" @click.prevent="setActive('meal')"
              >火车餐</a
            >
          </li>
        </ul>
      </nav>
    </aside>
    <header class="header">
      <div style="margin-right: auto">{{ displayName }},欢迎您！</div>
      <div class="header-nav">
        <a href="#" @click.prevent="goToHistoryOrder">历史订单</a>
        <a href="#" @click.prevent="goToMessages">消息中心</a>
        <a href="https://gitee.com/wangzi-ma/software-engineering-homework" target="_blank"
          >关于我们</a
        >
      </div>
      <div class="avatar-wrapper">
        <img class="avatar" src="/logo.png" alt="头像" />
        <ul class="dropdown-menu">
          <li><a href="#" @click.prevent="goToPersonalCenter">个人中心</a></li>
          <li><a href="#" @click.prevent="goToWallet">我的钱包</a></li>
          <li><a href="#" @click.prevent="logout">退出登录</a></li>
        </ul>
      </div>
    </header>
    <!-- 中间主内容区域：火车列表显示 -->
    <main class="main-content">
      <div class="date-nav">
        <button
          v-for="d in dateList"
          :key="d.date"
          :class="{ active: d.date === selectedDate }"
          @click="changeDate(d.date)"
        >
          {{ d.label }}
        </button>
      </div>
      <div class="content-layout">
        <!-- 左侧列车列表 -->
        <div class="train-list">
          <div class="train-header">
            <span class="route">{{ from }}-{{ to }}</span>
            <span class="trip-info"
              >单程 {{ selectedDate }} (共{{ filteredTrains.length }}车次)</span
            >
            <!-- 新增：按钮式排序栏 -->
            <div class="sort-buttons">
              <button
                :class="{ active: sortOption === 'departure' }"
                @click="sortOption = 'departure'"
              >
                🚆 出发时间
              </button>
              <button
                :class="{ active: sortOption === 'duration' }"
                @click="sortOption = 'duration'"
              >
                ⏱ 总时长
              </button>
            </div>
          </div>
          <div v-if="loading">加载中...</div>
          <div v-else-if="trains.length === 0">暂无符合条件的车次</div>
          <ul v-else class="train-list-ul">
            <li v-for="train in filteredTrains" :key="train.trainNumber" class="train-card">
              <div class="card-content">
                <!-- 左：起点时间和站点 -->
                <div class="train-time-station">
                  <div class="time">{{ train.departureTime }}</div>
                  <div class="station">{{ train.from }}</div>
                </div>
                <!-- 中：箭头 + 耗时 + 列车号 -->
                <div class="train-middle">
                  <div class="duration">{{ train.duration }}</div>
                  <svg class="arrow-svg" viewBox="0 0 80 10" xmlns="http://www.w3.org/2000/svg">
                    <line x1="0" y1="5" x2="70" y2="5" stroke="#ccc" stroke-width="2" />
                    <polygon points="70,2 80,5 70,8" fill="#ccc" />
                  </svg>
                  <div class="train-number">{{ train.trainNumber }}</div>
                </div>
                <!-- 右：终点时间和站点 -->
                <div class="train-time-station">
                  <div class="time">{{ train.arrivalTime }}</div>
                  <div class="station">{{ train.to }}</div>
                </div>
                <!-- 票价与座位信息 + 订按钮 -->
                <div class="train-right">
                  <div class="price">￥{{ getLowestPrice(train) }}</div>
                  <div class="seats">
                    <div
                      v-for="(seat, seatType) in filteredSeats(train.trainType, train.seats)"
                      :key="seatType"
                      class="seat-item"
                    >
                      {{ seatType }}{{ seat.count }}张
                    </div>
                  </div>
                </div>
                <!-- “订”按钮 -->
                <button class="book-btn" @click="book(train)">订</button>
              </div>
              <!-- 新增的座位选择卡片 -->
              <div v-if="expandedTrain === train.trainNumber" class="seat-selection-card">
                <div class="seat-options">
                  <div
                    v-for="(seat, seatType) in filteredSeats(train.trainType, train.seats)"
                    :key="seatType"
                    class="seat-option"
                  >
                    <div class="seat-info">
                      <span class="seat-type">{{ seatType }}</span>
                      <span class="seat-count" v-if="seat.count > 0">余{{ seat.count }}张</span>
                      <span class="seat-count" v-else>无票</span>
                    </div>
                    <div class="price-and-button">
                      <span class="seat-price">￥{{ seat.price }}</span>
                      <button
                        class="select-btn"
                        :disabled="seat.count <= 0 || isDeparted(selectedDate, train.departureTime)"
                        @click="selectSeat(train, seatType)"
                      >
                        预订
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </li>
          </ul>
        </div>
        <!-- 右侧筛选功能区域 -->
        <div class="sidebar-right">
          <h3>筛选</h3>
          <hr class="divider" />
          <div class="filter-section">
            <div class="filter-title">车次类型</div>
            <div class="filter-options">
              <label><input type="checkbox" value="G" v-model="trainTypeFilter" /> 高铁 (G)</label>
              <label><input type="checkbox" value="D" v-model="trainTypeFilter" /> 动车 (D)</label>
              <label
                ><input type="checkbox" value="other" v-model="trainTypeFilter" /> 其他
                (Z/T/K)</label
              >
            </div>
          </div>
          <hr class="divider" />
          <div class="filter-section">
            <div class="filter-title">出发时间</div>
            <div class="filter-options">
              <label
                ><input type="checkbox" value="0-6" v-model="departureTimeFilter" />
                00:00-06:00</label
              >
              <label
                ><input type="checkbox" value="6-12" v-model="departureTimeFilter" />
                06:00-12:00</label
              >
              <label
                ><input type="checkbox" value="12-18" v-model="departureTimeFilter" />
                12:00-18:00</label
              >
              <label
                ><input type="checkbox" value="18-24" v-model="departureTimeFilter" />
                18:00-24:00</label
              >
            </div>
          </div>
          <hr class="divider" />
          <div class="filter-section">
            <div class="filter-title">到达时间</div>
            <div class="filter-options">
              <label
                ><input type="checkbox" value="0-6" v-model="arrivalTimeFilter" />
                00:00-06:00</label
              >
              <label
                ><input type="checkbox" value="6-12" v-model="arrivalTimeFilter" />
                06:00-12:00</label
              >
              <label
                ><input type="checkbox" value="12-18" v-model="arrivalTimeFilter" />
                12:00-18:00</label
              >
              <label
                ><input type="checkbox" value="18-24" v-model="arrivalTimeFilter" />
                18:00-24:00</label
              >
            </div>
          </div>
          <hr class="divider" />
          <div class="filter-actions">
            <button class="reset-btn" @click="resetFilters">重置筛选</button>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import api from '@/utils/api'
import type { TrainDisplay } from '@/types/train'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()
const activeTab = ref('train')
const displayName = ref('')
const from = route.query.from as string
const to = route.query.to as string
const date = route.query.date as string
const trains = ref<TrainDisplay[]>([])
const totalTrains = ref<number>(0) // 新增：车次总数
const loading = ref(true)
const seatTypes = ['商务座', '一等座', '二等座', '软卧', '硬卧', '软座', '硬座']

// 座位类型枚举
const SEAT_TYPES = {
  1: { name: '一等座', code: 1 },
  2: { name: '二等座', code: 2 },
  3: { name: '商务座', code: 3 },
}

function getSeatTypeName(code: number): string {
  return SEAT_TYPES[code as keyof typeof SEAT_TYPES]?.name || '未知类型'
}
const selectedDate = ref(date) // 初始日期来自路由
const dateList = ref<{ date: string; label: string }[]>([])
const expandedTrain = ref<string | null>(null) //座位卡片响应式变量
const sortOption = ref<'departure' | 'duration'>('departure')

/*筛选功能逻辑*/
const trainTypeFilter = ref<string[]>([])
const departureTimeFilter = ref<string[]>([])
const arrivalTimeFilter = ref<string[]>([])
const filteredTrains = computed(() => {
  const result = trains.value.filter((train) => {
    const type = train.trainType
    const isOtherType = ['Z', 'T', 'K'].includes(type)
    const matchesTrainType =
      trainTypeFilter.value.length === 0 ||
      trainTypeFilter.value.includes(type) ||
      (trainTypeFilter.value.includes('other') && isOtherType)
    const inTimeRange = (timeStr: string, ranges: string[]) => {
      const hour = parseInt(timeStr.split(':')[0])
      return (
        ranges.length === 0 ||
        ranges.some((range) => {
          const [start, end] = range.split('-').map(Number)
          return hour >= start && hour < end
        })
      )
    }
    const matchesDeparture = inTimeRange(train.departureTime, departureTimeFilter.value)
    const matchesArrival = inTimeRange(train.arrivalTime, arrivalTimeFilter.value)
    return matchesTrainType && matchesDeparture && matchesArrival
  })
  // 新增排序
  return result.slice().sort((a, b) => {
    if (sortOption.value === 'departure') {
      /*出发时间排序*/
      return a.departureTime.localeCompare(b.departureTime)
    } else if (sortOption.value === 'duration') {
      const aDuration =
        parseInt(a.duration.match(/\d+/g)?.[0] || '0') * 60 +
        parseInt(a.duration.match(/\d+/g)?.[1] || '0')
      const bDuration =
        parseInt(b.duration.match(/\d+/g)?.[0] || '0') * 60 +
        parseInt(b.duration.match(/\d+/g)?.[1] || '0')
      return aDuration - bDuration
    }
    return 0
  })
})
/*const filteredTrains = computed(() => {
  return trains.value.filter(train => {
    // 车次类型筛选
    const type = train.trainType
    const isOtherType = ['Z', 'T', 'K'].includes(type)
    const matchesTrainType =
      trainTypeFilter.value.length === 0 ||
      trainTypeFilter.value.includes(type) ||
      (trainTypeFilter.value.includes('other') && isOtherType)
    // 时间段转换函数
    const inTimeRange = (timeStr: string, ranges: string[]) => {
      const hour = parseInt(timeStr.split(':')[0])
      return ranges.length === 0 || ranges.some(range => {
        const [start, end] = range.split('-').map(Number)
        return hour >= start && hour < end
      })
    }
    const matchesDeparture = inTimeRange(train.departureTime, departureTimeFilter.value)
    const matchesArrival = inTimeRange(train.arrivalTime, arrivalTimeFilter.value)
    return matchesTrainType && matchesDeparture && matchesArrival
  })
})*/
function resetFilters() {
  trainTypeFilter.value = []
  departureTimeFilter.value = []
  arrivalTimeFilter.value = []
  expandedTrain.value = null //重置筛选时重置展开状态
}
// 新增：监听筛选条件和排序选项的变化
watch(
  [
    () => trainTypeFilter.value,
    () => departureTimeFilter.value,
    () => arrivalTimeFilter.value,
    () => sortOption.value,
  ],
  () => {
    expandedTrain.value = null // 重置展开状态
  },
  { deep: true }, // 深度监听数组类型的筛选条件
)

/*初始化从“今天”起连续 7 天的日期导航列表，用于渲染按钮。*/
function initDateList() {
  const list = []
  for (let i = 0; i < 7; i++) {
    const d = dayjs().add(i, 'day')
    const dateStr = d.format('MM-DD')
    let label = ''
    if (i === 0) {
      label = `${dateStr} 今天`
    } else if (i === 1) {
      label = `${dateStr} 明天`
    } else {
      const weekday = '日一二三四五六'[d.day()]
      label = `${dateStr} 星期${weekday}`
    }
    list.push({
      date: d.format('YYYY-MM-DD'), // 发送给后端用
      label, // 显示给用户用，如“05-25 Saturday”
    })
  }
  dateList.value = list
}
function changeDate(d: string) {
  selectedDate.value = d
  expandedTrain.value = null // 新增：切换日期时重置展开状态
  sortOption.value = 'departure' // 🔁 新增：切换日期时重置排序
  router.replace({
    path: '/train-list',
    query: {
      from,
      to,
      date: d,
    },
  })
  resetFilters() // 重置筛选项
  fetchTrains() // 调用后端接口
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function formatTrainData(rawList: any[], stationMap?: Map<number, string>): TrainDisplay[] {
  return rawList.map((train: any) => {
    const seats: Record<string, { count: number; price: number }> = {}

    // 处理新的库存数据结构
    if (train.seatTypeInventories) {
      console.log(
        `列车 ${train.trainNumber} 库存统计: 总座位=${train.totalSeats}, 可用=${train.availableSeats}, 已售=${train.soldSeats}`,
      )

      // 使用后端返回的库存信息
      Object.entries(train.seatTypeInventories).forEach(
        ([seatTypeName, inventory]: [string, any]) => {
          console.log(
            `座位类型 ${seatTypeName}: ${inventory.availableSeats}/${inventory.totalSeats} 可用, 价格: ¥${inventory.minPrice || inventory.averagePrice}`,
          )
          seats[seatTypeName] = {
            count: inventory.availableSeats || 0,
            price: inventory.minPrice || inventory.averagePrice || 0,
          }
        },
      )
    } else {
      console.log(`列车 ${train.trainNumber} 没有库存信息，使用默认值`)
      // 兼容旧数据结构
      for (let i = 0; i < seatTypes.length; i++) {
        const type = seatTypes[i]
        seats[type] = {
          count: train.availableSeats?.[i] ?? 0,
          price: train.seatPrices?.[i] ?? 0,
        }
      }
    }

    // 处理时间，去掉秒数
    const formatTime = (timeStr: string) => {
      if (!timeStr) return '--:--'
      return dayjs(`2023-01-01 ${timeStr}`).format('HH:mm')
    }

    return {
      trainNumber: train.trainNumber,
      trainType: train.trainType,
      from:
        stationMap?.get(train.departureStationId) ||
        train.departureStationName ||
        train.departureStation,
      to:
        stationMap?.get(train.terminalStationId) ||
        train.terminalStationName ||
        train.terminalStation,
      departureTime: formatTime(train.departureTime),
      arrivalTime: formatTime(train.arrivalTime),
      duration: formatDuration(train.duration),
      seats,
    }
  })
}
function formatDuration(minutes: number) {
  //化为“X小时Y分”形式
  const h = Math.floor(minutes / 60)
  const m = minutes % 60
  return `${h}小时${m}分`
}
async function fetchTrains() {
  loading.value = true
  try {
    // 先获取所有列车
    const trainsRes = await api.get('/api/trains')
    console.log('后端返回的列车数据:', trainsRes.data)

    // 获取所有车站信息
    const stationsRes = await api.get('/api/stations')
    console.log('后端返回的车站数据:', stationsRes.data)

    // 创建车站ID到站名的映射
    const stationMap = new Map()
    stationsRes.data.forEach((station: any) => {
      stationMap.set(station.stationId, station.stationName)
    })

    console.log('查询条件 - from:', from, 'to:', to, 'date:', selectedDate.value)

    // 在前端过滤符合条件的列车
    const filteredTrains = trainsRes.data.filter((train: any) => {
      const departureStationName = stationMap.get(train.departureStationId)
      const terminalStationName = stationMap.get(train.terminalStationId)

      console.log(
        '检查列车:',
        train.trainNumber,
        '始发站:',
        departureStationName,
        '终点站:',
        terminalStationName,
      )

      // 根据始发站和终点站进行过滤
      const departureMatch = !from || departureStationName?.includes(from)
      const terminalMatch = !to || terminalStationName?.includes(to)

      return departureMatch && terminalMatch
    })

    // 为每个列车获取库存信息
    const trainsWithInventory = await Promise.all(
      filteredTrains.map(async (train: any) => {
        try {
          // 使用指定日期查询库存
          const inventoryRes = await api.get(`/api/trains/${train.trainId}/inventory/date`, {
            params: {
              travelDate: selectedDate.value,
            },
          })
          console.log(
            `列车 ${train.trainNumber} 在 ${selectedDate.value} 的库存信息:`,
            inventoryRes.data,
          )
          // 直接返回库存数据，不合并基础列车信息
          return {
            ...inventoryRes.data,
            // 保留基础列车信息
            trainId: train.trainId,
            trainNumber: train.trainNumber,
            trainType: train.trainType,
            departureStationId: train.departureStationId,
            terminalStationId: train.terminalStationId,
            departureTime: train.departureTime,
            arrivalTime: train.arrivalTime,
            duration: train.duration,
          }
        } catch (error) {
          console.error(`获取列车 ${train.trainNumber} 库存失败:`, error)
          // 如果指定日期查询失败，尝试查询今天的库存
          try {
            const fallbackRes = await api.get(`/api/trains/${train.trainId}/inventory`)
            console.log(`列车 ${train.trainNumber} 今天的库存信息:`, fallbackRes.data)
            return {
              ...fallbackRes.data,
              // 保留基础列车信息
              trainId: train.trainId,
              trainNumber: train.trainNumber,
              trainType: train.trainType,
              departureStationId: train.departureStationId,
              terminalStationId: train.terminalStationId,
              departureTime: train.departureTime,
              arrivalTime: train.arrivalTime,
              duration: train.duration,
            }
          } catch (fallbackError) {
            console.error(`获取列车 ${train.trainNumber} 今天库存也失败:`, fallbackError)
            return train
          }
        }
      }),
    )

    trains.value = formatTrainData(trainsWithInventory, stationMap)
    totalTrains.value = filteredTrains.length
  } catch (err) {
    console.error('查询失败:', err)
  } finally {
    loading.value = false
  }
}
onMounted(() => {
  displayName.value = localStorage.getItem('username') || ''
})
onMounted(() => {
  initDateList()
  fetchTrains()
})

type SeatInfo = {
  count: number
  price: number
}
type SeatMap = Record<string, SeatInfo>
function filteredSeats(trainType: string, seats: SeatMap): SeatMap {
  const seatMap: Record<string, string[]> = {
    G: ['商务座', '一等座', '二等座'],
    D: ['一等座', '二等座'],
    Z: ['软卧', '硬卧', '软座', '硬座'],
    T: ['软卧', '硬卧', '软座', '硬座'],
    K: ['软卧', '硬卧', '软座', '硬座'],
  }
  const allowed = seatMap[trainType] || Object.keys(seats)
  const filtered = Object.fromEntries(
    Object.entries(seats).filter(([type]) => allowed.includes(type)),
  )
  return filtered
}
function getLowestPrice(train: { trainType: string; seats: SeatMap }): number | string {
  const seats = filteredSeats(train.trainType, train.seats)
  const prices = Object.values(seats)
    .map((s) => s.price)
    .filter((p) => p != null)
  return prices.length > 0 ? Math.min(...prices) : '--'
}
function book(train: { trainNumber: string }) {
  // 如果已经展开，则关闭；否则展开
  expandedTrain.value = expandedTrain.value === train.trainNumber ? null : train.trainNumber
}
// 新增选择座位函数
function selectSeat(train: TrainDisplay, seatType: string) {
  console.log('选择车次:', train.trainNumber, '座位类型:', seatType)
  // 这里可以跳转到支付页面
  router.push({
    path: '/trainBooking',
    query: {
      userName: displayName.value,
      trainNumber: train.trainNumber,
      from: train.from,
      to: train.to,
      duration: train.duration,
      date: selectedDate.value,
      seatType: seatType,
      price: train.seats[seatType].price,
    },
  })
}
//车次已过期则不显示
function isDeparted(date: string, time: string): boolean {
  const departureDateTime = new Date(`${date}T${time}`)
  const now = new Date()
  return departureDateTime <= now
}

function goToHistoryOrder() {
  router.push({
    path: '/history',
    query: { username: displayName.value },
  })
}
function goToMessages() {
  router.push({
    path: '/messages',
    query: { username: displayName.value },
  })
}
function goToWallet() {
  // 跳转到钱包页面并传递昵称参数
  router.push({
    path: '/wallet', // 钱包页面路由路径
    query: { username: displayName.value }, // 传递参数
  })
}
function goToPersonalCenter() {
  router.push({
    path: '/center',
    query: { username: displayName.value },
  })
}
function logout() {
  localStorage.removeItem('token')
  router.push('/login')
}
function setActive(tab: string) {
  activeTab.value = tab
  if (tab === 'hotel') {
    router.push('/hotel')
  } else if (tab === 'train') {
    router.push('/home')
  } else if (tab === 'meal') {
    router.push('/meal') // 当前页可写死或省略
  }
}
</script>

<style scoped>
.train-list {
  padding: 20px;
}
.train-item {
  padding: 10px;
  border-bottom: 1px solid #ccc;
}
/* 原有样式保留不变，这里省略 layout 部分重复样式 */
/* 添加重置样式 */
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
html,
body {
  height: 100%;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
}
/* 容器布局 */
.home-layout {
  display: grid;
  grid-template-columns: 200px 1fr;
  transition: grid-template-columns 0.3s ease;
  grid-template-rows: 60px 1fr;
  grid-template-areas:
    'sidebar header'
    'sidebar main';
  height: 100vh;
  width: 100vw; /* 保证横向占满 */
}
.home-layout.collapsed {
  grid-template-columns: 60px 1fr;
}
/* 左侧边栏 */
.sidebar {
  grid-area: sidebar;
  background-color: #0086f6;
  color: white;
  padding: 20px;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  transition: width 0.3s ease;
  overflow: hidden;
  position: relative;
}
/* 分隔线样式 */
.sidebar-divider {
  border: none;
  border-top: 1px solid rgba(255, 255, 255, 0.3);
  /*margin: 10px 0 20px;*/
  margin: 8px 0 16px;
}
/* 调整导航项间距和分隔 */
.sidebar li + li {
  border-top: 1px solid rgba(255, 255, 255, 0.15); /* 每项之间加线 */
  padding-top: 10px;
  margin-top: 8px;
}
/* 标题 */
.sidebar h1 {
  font-size: 28px;
  margin-bottom: 20px;
  text-align: center;
}
/* 导航样式 */
.sidebar ul {
  list-style: none;
  padding: 0;
  width: 100%;
}
.sidebar li {
  margin: 8px 0;
}
.sidebar a {
  display: flex;
  align-items: center;
  gap: 10px;
  color: white;
  padding: 10px;
  border-radius: 6px;
  text-decoration: none;
  transition: background-color 0.2s ease;
}
.sidebar a:hover {
  background-color: rgba(255, 255, 255, 0.1);
}
.sidebar a.active {
  background-color: rgba(255, 255, 255, 0.25);
  font-weight: bold;
}

/* 右上角头部 */
.header {
  grid-area: header;
  display: flex;
  justify-content: space-between; /* 左右分开 */
  align-items: center;
  padding: 0 20px;
  background-color: #f0f0f0;
  border-bottom: 1px solid #ddd;
}
.header-nav {
  display: flex;
  margin-right: 20px;
}
.header-nav a {
  margin-right: 20px;
  color: #333;
  text-decoration: none;
}
.header-nav a:hover {
  text-decoration: underline;
}
/* 头像 */
.avatar-wrapper {
  position: relative;
  display: inline-block;
  cursor: pointer;
  padding-top: 10px; /* 保证 hover 区域连贯 */
}
.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover; /* 防止图片变形，裁剪填充 */
  transition: box-shadow 0.3s;
}
.avatar:hover {
  box-shadow: 0 0 8px rgba(0, 134, 246, 0.5);
}
/* 下拉菜单样式 */
.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  list-style: none;
  padding: 10px 0;
  margin: 0;
  min-width: 140px;
  display: none;
  z-index: 100;
}
.dropdown-menu li {
  padding: 10px 20px;
}
.dropdown-menu li a {
  text-decoration: none;
  color: #333;
  display: block;
  transition: background 0.2s;
}
.dropdown-menu li:hover {
  background-color: #f0f0f0;
}
/* 显示菜单：鼠标悬停时 */
.avatar-wrapper:hover .dropdown-menu {
  display: block;
}

.main-content {
  grid-area: main;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 15px;
  background-color: #f5f7fa; /* 主区域背景可选 */
}
/*顶部日期栏导航*/
.date-nav {
  display: flex;
  gap: 14px;
  margin: 20px 0 16px; /* 顶部留空隙 */
  justify-content: center;
  flex-wrap: wrap;
}
.date-nav button {
  padding: 14px 22px;
  font-size: 16px;
  color: #333;
  background-color: #f0f0f0; /* 非active按钮背景 */
  border: 1px solid #dcdfe6;
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 110px;
  text-align: center;
  font-weight: 500;
}
.date-nav button:hover {
  background-color: #ecf5ff;
  border-color: #409eff;
  color: #409eff;
}
.date-nav button.active {
  background-color: #409eff;
  border-color: #409eff;
  color: white;
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.4);
}

.content-layout {
  flex: 1;
  display: flex;
  gap: 24px;
  background-color: #f6faff; /* 非常淡的蓝色 */
  padding: 24px;
  overflow-y: auto;
  min-height: 0; /* 重要！防止内容溢出父容器 */
  height: 100%; /* 撑满可视区域 */
  align-items: stretch; /* 默认即可两栏等高 */
}
.train-list {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%; /* 保证高度随右侧一致 */
  position: relative; /* 确保相对定位上下文 */
}
.train-header {
  /*顶部汉字*/
  display: flex;
  align-items: baseline;
  gap: 15px; /* 两段文字间距 */
  margin-bottom: 20px;
  justify-content: space-between; /* 两端对齐：左侧信息 + 右侧按钮 */
  padding: 0 40px; /* 👈 左右内边距 */
}
.sort-buttons {
  display: flex;
  gap: 8px;
}
.sort-buttons button {
  padding: 4px 10px;
  border: 1px solid #ccc;
  background: #f8f8f8;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s ease; /* 平滑过渡效果 */
}
.sort-buttons button:hover {
  background: #e0eaff;
  border-color: #409eff;
  color: #409eff;
}
.sort-buttons button.active {
  background: #409eff;
  color: white;
  border-color: #409eff;
}

.route {
  font-size: 19px;
  font-weight: 600;
  color: #333;
}
.trip-info {
  font-size: 17px;
  color: #666; /* 淡灰色 */
  font-weight: 700; /* 或 600，700，根据你想要的粗细 */
  margin-top: 4px;
}
.train-list-ul {
  padding: 0;
  list-style: none;
}
/*车次卡片UI*/
.train-card {
  border-radius: 10px;
  padding: 16px;
  margin-bottom: 20px;
  background: #fff;
  transition:
    margin-bottom 0.2s ease,
    border-radius 0.2s ease;
}
/* 调整卡片容器，当展开时添加底部圆角 */
.train-card.expanded {
  border-radius: 10px 10px 0 0; /* 只圆角顶部 */
  margin-bottom: 0; /* 移除底部间距 */
}
.card-content {
  display: flex;
  align-items: center;
  justify-content: flex-start; /* 修改为 flex-start */
  gap: 16px;
  flex-wrap: wrap;
  max-width: 100%;
  padding-left: 30px; /* 添加左侧内边距 */
}
.train-time-station {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 80px;
}
.time {
  font-size: 25px;
  font-weight: 900;
  color: #282828;
}
.station {
  font-size: 15px;
  font-weight: 850;
  color: #666666;
}
.train-middle {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 120px; /* 稍微加宽 */
  position: relative;
}
.arrow-svg {
  width: 80px;
  height: 10px;
  margin: 4px 0;
}
.duration,
.train-number {
  font-size: 13px;
  color: #999999;
  font-weight: normal;
  margin: 2px 0;
}
.train-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  flex: 1;
}
.price {
  font-size: 24px;
  font-weight: 1000;
  color: #2196f3;
  margin-bottom: 4px;
  text-align: right; /* 文字右对齐 */
  width: 100%; /* 让文字占满容器宽度，方便右对齐 */
}
.seats {
  font-size: 13px;
  font-weight: normal;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: flex-end;
  color: #999999; /* 座位及数量颜色变淡 */
  width: 100%; /* 让座位占满宽度方便对齐 */
  text-align: right; /* 文字右对齐 */
}
.seat-item {
  background: none;
  padding: 4px 8px;
  border-radius: 4px;
}
.book-btn {
  padding: 12px 16px;
  font-size: 20px;
  font-weight: 800; /* 订字稍微加粗 */
  background-color: #ff7a45;
  color: white;
  border: 1px solid #ff7a45;
  border-radius: 8px;
  cursor: pointer;
  white-space: nowrap;
  box-shadow: 0 4px 6px rgba(255, 122, 69, 0.4);
  transition: background-color 0.2s ease;
}
.book-btn:hover {
  background-color: #f4511e; /* 悬停时稍加深 */
  box-shadow: 0 6px 8px rgba(244, 81, 30, 0.6);
  transform: translateY(-2px);
}
.book-btn:active {
  box-shadow: 0 3px 5px rgba(244, 81, 30, 0.5);
  transform: translateY(0);
}

/*座位展示卡片*/
.seat-selection-card {
  padding: 20px;
  background: #f9f9f9;
  border-radius: 0 0 12px 12px; /* 只圆角底部 */
  border-top: none; /* 移除顶部边框 */
  /* 添加负边距与上方卡片视觉衔接 */
  margin: 12px -16px -16px;
  width: calc(100% + 32px); /* 补偿负边距 */
}
.seat-options {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.seat-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
}
.seat-info {
  display: flex;
  align-items: center;
  gap: 50px; /* 增大间距到40px */
  flex-grow: 1;
  margin-left: 30px; /* 新增：左侧额外外边距 */
}
.seat-type {
  min-width: 100px; /* 改为最小宽度保证空间 */
  font-weight: 700; /* 加粗 */
  font-size: 20px; /* 增大字号 */
  color: #333;
}
.seat-count {
  width: 100px; /* 增大宽度 */
  font-size: 15px; /* 增大字号 */
  color: #666;
}
.price-and-button {
  display: flex;
  align-items: center;
  gap: 20px; /* 价格和按钮间距 */
}
.seat-price {
  font-size: 24px; /* 增大字号 */
  font-weight: 1000; /* 加粗 */
  color: #2196f3;
  min-width: 100px; /* 确保足够宽度 */
  text-align: right; /* 右对齐 */
}
.select-btn {
  padding: 12px 18px; /* 增大按钮尺寸 */
  font-size: 18px; /* 增大字号 */
  font-weight: 600;
  background: #ff7a45;
  color: white;
  border: none;
  border-radius: 6px; /* 增大圆角 */
  cursor: pointer;
  transition: all 0.2s ease; /* 添加过渡效果 */
  min-width: 80px; /* 确保按钮宽度一致 */
}
.select-btn:hover {
  background: #f4511e; /* 悬停效果 */
  transform: translateY(-1px);
}
.select-btn:active {
  transform: translateY(0);
}
.select-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

/*右侧筛选区*/
.sidebar-right {
  font-size: 18px;
  width: 320px; /* 更宽一点 */
  background-color: #fff;
  padding: 16px;
  border-radius: 10px;
  height: 666px; /*筛选区高度*/
  box-sizing: border-box;
}
.filter-section {
  margin-bottom: 20px;
}
.filter-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}
.filter-options label {
  display: block;
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: 500;
}
.divider {
  border: none;
  border-top: 1px solid #e0e0e0;
  margin: 16px 0;
}
.filter-actions {
  text-align: center;
}
.reset-btn {
  padding: 10px 16px;
  background-color: #f0f0f0;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  transition: background-color 0.3s ease;
}
.reset-btn:hover {
  background-color: #e0e0e0;
}
</style>
